#!/usr/bin/env python
# coding: utf-8

'''
适用于io密集型的场景
'''
import concurrent.futures
import urllib.request

URLS = ['http://www.163.com/',
        'http://www.sina.com.cn/',
        'https://www.taobao.com/',
        'http://www.jd.com/',
        'http://www.youku.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    '''
    一个需要长时间等待的io操作
    :param url: 访问的网站url
    :param timeout: 超时时间（S）， int/float
    :return: 网站返回的内容
    '''
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
#创建一个用于执行异步方法的executor，max_workers数量必须大于或等于任务数，否则会死锁
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    #executor.submit(task_func, *args, **kwargs)返回future对象
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    '''concurrent.futures.as_completed(futures, timeout),传入一个包含多个任务future对象的可迭代对象，
    并从中yield出已完成task的future'''
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result() #获取任务执行的结果
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))